package com.neusoft.resturant.controller;


import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.utils.R;
import com.neusoft.resturant.common.utils.SecurityUtils;
import com.neusoft.resturant.entity.SysUser;
import com.neusoft.resturant.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: Daniel
 * @date: 2023-10-26 08:41
 **/
@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController{

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {

        SysUser user = userService.selectUserByUserName(sysUser.getUserName());
        System.out.println(user);
        if (user == null) {
            return R.error(404, "用户不存在");
        }
        boolean ok = SecurityUtils.matchesPassword(sysUser.getPassword(), user.getPassword());
        System.out.println(ok);
        if (!ok) {
            return R.error(404, "账号密码错误");
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println(token);
        String jsonStr = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(token, jsonStr, 1, TimeUnit.HOURS);
        return R.success().put("token", token);
    }


    @GetMapping
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String user = (String) redisTemplate.opsForValue().get(token);
        SysUser sysUser = JSON.parseObject(user, SysUser.class);
        return R.success(sysUser);
    }

    @GetMapping("/get")
    public R testInterceptor(HttpServletRequest request) {
        Long userId = this.getUserId();
        System.out.println("userId:"+userId);
        SysUser curUser = this.getCurUser();
        System.out.println("curUser:" + curUser);
        return R.success(curUser);
    }


}
